//
//  SDNetOperation.m
//  SDDataTest
//
//  Created by ding wei on 12-10-4.
//  Copyright (c) 2012年 sodao. All rights reserved.
//

#import "SDNetOperation.h"
#import "JSON.h"

@implementation SDNetOperation
-(NSString*)sendRequestByName:(NSString*)name
                     getParam:(NSDictionary*)get
                    postParam:(NSDictionary*)post
                    restParam:(NSDictionary*)rest
                     postType:(int)pt
                        token:(NSString*)token
                     deviceID:(NSString*)deviceID
                responseBlock:(CompleteWithString)complete
                    failBlock:(FailWithString)fail
{
    NSString* url;
    NSString* baseURL = nil;
#if isTestServer
    baseURL = [_URLMap baseTestURL];
#else
    baseURL = [_URLMap baseURL];
#endif
    NSArray* rests = [_URLMap restParams:name];
    NSArray* gets = [_URLMap getParams:name];
    NSString* uri = [_URLMap uriByKey:name];
    RequestType type = [_URLMap typeByKey:name];
    url = [baseURL stringByAppendingFormat:@"/%@",uri];
    if (type == RequestType_Rest||type == RequestType_GetRest||type == RequestType_PostRest) {
        for (int i = 0;i<gets.count;i++) {
            NSString* key = [rests objectAtIndex:i];
            NSString* value = [rest objectForKey:key];
            if (value != nil) {
                url = [url stringByAppendingFormat:@"/%@",value];
            }else{
                NSLog(@"request param error:%@------%@",key,name);
                return NotificationParamError;
            }
        }
    }
    if (type == RequestType_Get || type == RequestType_GetRest) {
        for (int i = 0;i<gets.count;i++) {
            NSString* key = [gets objectAtIndex:i];
            NSString* value = [get objectForKey:key];
            if (value!=nil) {
                if (i==0) {
                    url = [url stringByAppendingFormat:@"?%@=%@",key,value];
                }else{
                    url = [url stringByAppendingFormat:@"&%@=%@",key,value];
                }
            }
        }
    }
    ASIHTTPRequest* request;
    NSURL* ul = [NSURL URLWithString:url];
    if (type == RequestType_Rest||type == RequestType_GetRest||type == RequestType_PostRest) {
         request = [[ASIHTTPRequest alloc] initWithURL:ul];
        [request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
    }else{
        ASIFormDataRequest* form = [[ASIFormDataRequest alloc] initWithURL:ul];
        if (pt == 0) {
            
            if(post != nil)
            for (NSString* key in post.allKeys) {
                NSString* value = [post objectForKey:key];
                [form addPostValue:value forKey:key];
            }
        }else if (pt == 0) {
            SBJsonWriter* write = [[SBJsonWriter alloc] init];
            NSString* s = [write stringWithObject:post];
            [write release];
            NSData *data=[s dataUsingEncoding:NSUTF8StringEncoding];
            
            [form addRequestHeader:@"Content-Type" value:@"Application/JSON"];
            [form addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%d",[data length]]];
            [form appendPostData:data];
            [form setRequestMethod:@"POST"];
        }
        request = form;
        
    }
    
    [request addRequestHeader:@"appkey" value:[_URLMap APPKey]];
    [request setTimeOutSeconds:DefaultTimeOutSeconeds];
    [request setShouldContinueWhenAppEntersBackground:YES];
    if (token!=nil) {
        [request addRequestHeader:@"token" value:token];
    }
    if (deviceID!=nil) {
        [request addRequestHeader:@"device" value:deviceID];
    }

    [request setCompletionBlock:^(void){
        complete(request.responseString);
    }];
    [request setFailedBlock:^(void){
        NSLog(@"%@",request.error.description);
        fail(request.responseString, request.error);
        
    }];
    [_operationQueue addOperation:request];
    [request release];
    return nil;
       
}

-(id)init{
    self = [super init];
    if (!!self) {
        _operationQueue = [[NSOperationQueue alloc] init];
        _URLMap = [[SDNetURLMap alloc] init];
    }
    return self;
}
+(SDNetOperation*)shareInstance{
    static SDNetOperation* instance;
    if (instance == nil) {
        instance = [[SDNetOperation alloc] init];
    }
    return instance;
}
-(void)dealloc{
    [super dealloc];
    [_operationQueue cancelAllOperations];
    [_operationQueue release];
}

@end
